# -*- coding: utf-8 -*-
#!/usr/local/bin/python
# Author: yuxiangyu
# Date: Oct 22, 2021 4:03 PM
# =============================

'''
定时重启模型服务
'''
import os
import datetime
# 当前时间
now_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")


if __name__ == "__main__":
    print("----run code of models----")
    print("now time: ", now_time)

    # celery
    celery_status = "ps -ef | grep celery | grep -v grep | awk '{print $2}' | xargs kill -9"
    # 项目路径
    project_dir = "cd /data/ubuntu/project/tmp/pycharm_project_861"
    # 虚拟环境激活
    pyenv = "source /data/ubuntu/webserver/django2/bin/activate"
    # 重启 celery
    celery_run = "/data/ubuntu/webserver/django2/bin/python3 celery -A modelProject worker -B --loglevel=info"
    django_run = "/data/ubuntu/webserver/django2/bin/python3 manage.py runserver 127.0.0.1:8000"
    # 退出虚拟环境
    # pyenv_exist = "deactivate"
    # try:
    #     os.system(pyenv_exist)  # 退出
    # except:
    #     pass
    # try:
    #     os.system(pyenv)  # 尝试激活虚拟环境
    # except:
    #     pass
    try:
        os.system(project_dir) # 切换工作路径
        print("切换工作路径成功")
    except:
        pass
    try:
        os.system(celery_status) # 强制暂停 celery
    except:
        pass
    try:
        # 重启
        os.system(celery_run)
        print("---重启成功--", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    except SyntaxError as e:
        print("重启失败!!")
    finally:
        pass
        # os.system(pyenv_exist)